
const { Pool } = require('pg');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const pool = new Pool({
  user: 'postgres',
    host: 'localhost',
    database: 'postgres',
    password: '1234',
    port: 5432,
});

class auth{
    async registration(req, res) {
        try {
          const { email, password, username } = req.body;
          console.log(req.body)
          const hashedPassword = await bcrypt.hash(password, 7);
          const createUserQuery = 'INSERT INTO users (email, password_hash, username) VALUES ($1, $2, $3)'
          await pool.query(createUserQuery, [email, hashedPassword, username])
          res.status(201).send('User registered successfully')
        } catch (error) {
          console.error(error);
          res.status(500).send('Internal server error')
        }
      }
      
    async login (req, res){
        try {
          const { email, password } = req.body
          console.log(req.body)
          const getUserQuery = 'SELECT * FROM users WHERE email = $1'
          const { rows } = await pool.query(getUserQuery, [email])
          const user = rows[0]
          
          if (!user) {
            return res.status(401).send('Invalid email or password')
          }
      
          const passwordMatch = await bcrypt.compare(password, user.password_hash)
          if (!passwordMatch) {
            return res.status(401).send('Invalid email or password')
          }
      
          const accessToken = jwt.sign({ user: user }, 'secret_key', { expiresIn: '24h' })
          const refreshToken = jwt.sign({ user: user }, 'refresh_secret_key')
          res.json({ accessToken, refreshToken })
        } catch (error) {
          res.status(500).json({ error: error.message });
        }
      }
      
      // Обновление access token по refresh token
      async refreshToken(req, res){
        const { refreshToken } = req.body;
        if (!refreshToken) {
          return res.status(401).send('Refresh token is required')
        }
        jwt.verify(refreshToken, 'refresh_secret_key', (err, user) => {
          if (err) {
            return res.status(403).send('Invalid refresh token')
          }
          const accessToken = jwt.sign({ email: user.email }, 'secret_key', { expiresIn: '30m' })
          res.json({ accessToken })
        });
      };
      
      async users(req, res){
        try {
          const queryText = `
            SELECT * FROM users;
          `;
      
          const result = await pool.query(queryText);
          const users = result.rows;
          console.log(users)
      
          const response = {
            users
            // next: nextOffset === 0 ? null : `http://localhost:${PORT}/api/reports?limit=${limit}&offset=${nextOffset}${(req.query.user_id != null) ? "&user_id=" + user_id : ""}${(req.query.status_id != null) ? "&status_id=" + status_id : ""}${(req.query.status_sort != null) ? "&status_sort=" + status_sort : ""}${(req.query.last_report != null) ? "&last_report=" + last_report : ""}`,
            // previous: previousOffset === null ? null : `http://localhost:${PORT}/api/reports?limit=${limit}&offset=${previousOffset}${(req.query.user_id != null) ? "&user_id=" + user_id : ""}${(req.query.status_id != null) ? "&status_id=" + status_id : ""}${(req.query.status_sort != null) ? "&status_sort=" + status_sort : ""}${(req.query.last_report != null) ? "&last_report=" + last_report : ""}`,
          };
    
          res.json(response);
        } catch (error) {
          res.status(500).send(error)
        }
      }
      
      
}
module.exports = new auth()